package com.ctyon.watchsdk.client;

import com.ctyon.watchsdk.protobuf.WatchMessage;

import java.util.concurrent.TimeUnit;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;


/**
 * 
* @Title: NettyClientFilter
* @Description: Netty客户端 过滤器
* @Version:1.0.0  
 */
public class ClientFilter extends ChannelInitializer<SocketChannel> {

    private long heartBeat;

    public ClientFilter(long heartBeat) {
        this.heartBeat = heartBeat;
    }

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline ph = ch.pipeline();
        /*
         * 解码和编码，应和服务端一致
         * */
        //入参说明: 读超时时间、写超时时间、所有类型的超时时间、时间格式
        ph.addLast(new IdleStateHandler(5, heartBeat, 0, TimeUnit.SECONDS));
        
        //传输的协议 Protobuf
        ph.addLast(new ProtobufVarint32FrameDecoder());
        ph.addLast(new ProtobufDecoder(WatchMessage.Msg.getDefaultInstance()));
        ph.addLast(new ProtobufVarint32LengthFieldPrepender());
        ph.addLast(new ProtobufEncoder());

        //传输的协议 字符串
        ph.addLast(new StringEncoder());
        ph.addLast(new StringDecoder());

        //业务逻辑实现类
        ph.addLast("clientHandler",new ClientHandler());

    }
}
